package com.meeting.meetingroom_api.repository;

import com.meeting.meetingroom_api.entity.MeetingRoom;
import com.meeting.meetingroom_api.enums.RoomStatus;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.Optional;

@Repository
public interface MeetingRoomRepository extends JpaRepository<MeetingRoom, Integer>, JpaSpecificationExecutor<MeetingRoom> {

    // 重写基础方法，默认过滤已删除的记录
    @Query("SELECT m FROM MeetingRoom m WHERE m.deleted = false")
    List<MeetingRoom> findAll();
    
    @Query("SELECT m FROM MeetingRoom m WHERE m.deleted = false")
    Page<MeetingRoom> findAll(Pageable pageable);
    
    @Query("SELECT m FROM MeetingRoom m WHERE m.roomId = :roomId AND m.deleted = false")
    Optional<MeetingRoom> findById(@Param("roomId") Integer roomId);

    // 原有方法改为过滤已删除记录
    @Query("SELECT m FROM MeetingRoom m WHERE m.name = :name AND m.deleted = false")
    Optional<MeetingRoom> findByName(@Param("name") String name);

    @Query("SELECT m FROM MeetingRoom m WHERE m.status = :status AND m.deleted = false")
    List<MeetingRoom> findByStatus(@Param("status") RoomStatus status);

    @Query("SELECT m FROM MeetingRoom m WHERE m.capacity >= :capacity AND m.deleted = false")
    List<MeetingRoom> findByCapacityGreaterThanEqual(@Param("capacity") Integer capacity);

    // 管理员专用：查询已删除的记录
    @Query("SELECT m FROM MeetingRoom m WHERE m.deleted = true")
    List<MeetingRoom> findDeleted();
    
    @Query("SELECT m FROM MeetingRoom m WHERE m.deleted = true")
    Page<MeetingRoom> findDeleted(Pageable pageable);
    
    // 根据ID查找（包括已删除的记录，用于软删除操作）
    @Query("SELECT m FROM MeetingRoom m WHERE m.roomId = :roomId")
    Optional<MeetingRoom> findByIdIncludeDeleted(@Param("roomId") Integer roomId);
    
    // 检查名称是否已存在（排除特定ID，用于更新时检查）
    @Query("SELECT CASE WHEN COUNT(m) > 0 THEN true ELSE false END FROM MeetingRoom m WHERE m.name = :name AND m.roomId != :excludeId AND m.deleted = false")
    boolean existsByNameAndIdNot(@Param("name") String name, @Param("excludeId") Integer excludeId);
}